package com.flink.elasticsearch;

import com.alibaba.fastjson.JSONObject;
import com.flink.entity.LogInfoDTO;
import com.flink.unit.Constant;
import org.apache.http.HttpHost;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;


public class ElasticSearchUtils {
    final static Constant constant =new Constant();

    private static Logger logger = LoggerFactory.getLogger(ElasticSearchUtils.class);
    private static RestHighLevelClient restHighLevelClient;


    //获取elasticsearch客户端对象
    public static RestHighLevelClient getClient() {
        RestClientBuilder restClientBuilder = RestClient.builder(
                new HttpHost(constant.es_host, Integer.valueOf(constant.es_port), "http"));
        restHighLevelClient = new RestHighLevelClient(restClientBuilder);
        return restHighLevelClient;
    }

    /**
     * 查询
     */
    private static  void getDataES() throws IOException {
        RestHighLevelClient client = getClient();
        // 1.	构建GetRequest请求。
        GetRequest getRequest = new GetRequest(constant.es_index, constant.es_type, "1");

        // 2.	使用RestHighLevelClient.get发送GetRequest请求，并获取到ES服务器的响应。
        GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);

        // 3.	将ES响应的数据转换为JSON字符串
        String json = getResponse.getSourceAsString();

        System.out.println(json);
    }

    /**
     * 新增
     */
    private static  void addDataES() throws IOException {
        //1.	构建IndexRequest对象，用来描述ES发起请求的数据。
        IndexRequest indexRequest = new IndexRequest(constant.es_index, constant.es_type);

        //2.	设置文档ID。
//        indexRequest.id(jobDetail.getId() + "");
        LogInfoDTO logInfoDTO = new LogInfoDTO();
        logInfoDTO.setLogDate(20210826000000L);
        logInfoDTO.setUuid("uuid");
        logInfoDTO.setGroupID("11673");
        logInfoDTO.setServiceName("测试service");
        //3.	使用FastJSON将实体类对象转换为JSON。
        String json = JSONObject.toJSONString(logInfoDTO);

        //4.	使用IndexRequest.source方法设置文档数据，并设置请求的数据为JSON格式。
        indexRequest.source(json, XContentType.JSON);
        RestHighLevelClient client = getClient();
        //5.	使用ES High level client调用index方法发起请求，将一个文档添加到索引中。
        IndexResponse index = client.index(indexRequest, RequestOptions.DEFAULT);

        System.out.println(JSONObject.toJSONString(index));
    }



    public static void main(String[] args) throws IOException {
//        getDataES();
        addDataES();
    }
}
